package com.dmz.czykt.util;


import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;

/**
 * @author lee
 */
@Slf4j
public class SocketClientUtil {
	static String Encoding = "UTF-8";
	private Socket client;
	private Writer writer;

	/**
	 * 构造函数
	 * 
	 * @param host
	 *            要连接的服务端IP地址
	 * @param port
	 *            要连接的服务端对应的监听端口
	 * @throws Exception
	 */
	public SocketClientUtil(String host, int port) throws Exception {
		// 与服务端建立连接
		this.client = new Socket(host, port);
        log.info("{}与服务端建立连接...", client);
	}

	/**
	 * 发送消息
	 * 
	 * @param msg
	 * @throws Exception
	 */
	public void send(String msg) throws Exception {
		// 建立连接后就可以往服务端写数据了
		if (writer == null) {
			writer = new OutputStreamWriter(client.getOutputStream(), Encoding);
		}
		writer.write(msg);
		// writer.write("eof\n");
		writer.flush();// 写完后要记得flush
//		client.shutdownOutput();
        log.info("{}消息发送成功【{}】", client, msg);
	}

	/**
	 * 接收消息
	 * 
	 * @throws Exception
	 */
	public String receive() throws Exception {
		// 写完以后进行读操作
		Reader reader = new InputStreamReader(client.getInputStream(), Encoding);
		// 设置接收数据超时间为60秒
		client.setSoTimeout(60000);
		char[] chars = new char[2048];
		int len;
		StringBuffer sb = new StringBuffer();
		while ((len = reader.read(chars)) != -1) {
			sb.append(new String(chars, 0, len));
		}
        log.info("{}消息收到了，内容:【{}】", client, sb.toString());
		reader.close();
		// 关闭连接
		writer.close();
		client.close();
		return sb.toString();
	}


	/**
	 * 
	 * @param str
	 *            补字符串 原始字符串
	 * @param len
	 *            长度
	 * @param pad
	 *            补的符号
	 * @param side
	 *            补在哪边
	 * @return
	 */
	public static String padding(String str, int len, String pad, String side) {
		String padding = "";
		for (int i = 0; i < (len - str.length()); i++) {
			padding += pad;
		}
		if (side.toUpperCase().equals("L")) {
			return padding + str;
		} else if (side.equals("R")) {
			return str + padding;
		}
		return str;
	}
}